package com.isasa.android.bluetoothpractice.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.dd.morphingbutton.MorphingButton;
import com.isasa.android.bluetoothpractice.R;
import com.isasa.android.bluetoothpractice.base.Action;
import com.isasa.android.bluetoothpractice.base.BaseApplication;
import com.isasa.android.bluetoothpractice.oss.OssConst;
import com.isasa.android.bluetoothpractice.service.RxBleService;
import com.isasa.android.bluetoothpractice.sound.GesturePlay;
import com.isasa.android.bluetoothpractice.util.BleDataDeal;
import com.isasa.android.bluetoothpractice.util.Cell;
import com.isasa.android.bluetoothpractice.util.CircularAnim;
import com.isasa.android.bluetoothpractice.util.ExcelUtil;

import java.util.ArrayList;
import java.util.List;

import static com.isasa.android.bluetoothpractice.oss.OssConst.endpoint;

public class GestureActivity extends AppCompatActivity implements BleDataDeal.OnReceivedOKListener,SensorEventListener,View.OnClickListener{
    private boolean flag_1=false;
    private boolean flag_2=false;
    private boolean flag_3=false;
    private boolean flag_4=false;
    private boolean flag_5=false;
    private boolean flag_6=false;
    private Button btn_open;
    private Button btn_to;
    private Button btn_rescan;
    private RxBleService mbleService;
    private GesturePlay player=GesturePlay.getPlayer();
    private GestureReceiver mreceiver = new GestureReceiver();
    private boolean sendFlag = false;

    private SensorManager sensorManager = null;
    private Sensor sensor = null;
    private Button button_lt;
    private Button button_rt;
    private Button button_pd;
    private Button button_biubiu;
    private MorphingButton button_1;
    private Button button_0;
    private Intent mintent = new Intent(Action.MOBILE_SENSOR);
    private Intent xintent = new Intent(Action.MOBILE_SENSOR);

    private Button btn_scan;
    //TODO:collect mobile phone data;
    private OSS oss;
    private Button btn_excel;
    private List<Cell> cells=new ArrayList<>();
    private int mid=0;

    private int mMode;
    private int mCount;

    @Override
    public void OnReceivedOK(int orderCode, final ArrayList<Integer> content, int contentLength) {
        if(orderCode==0x02){
            if(mMode==1){
                switch (content.get(0)){
                    case 0x01:
                        player.play(10);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CircularAnim.hide(button_pd).go();
                                CircularAnim.show(button_pd).go();
                            }
                        });
                        break;
                    case 0x02:
                        player.play(10);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CircularAnim.hide(button_pd).go();
                                CircularAnim.show(button_pd).go();
                            }
                        });
                        break;
                    case 0x04:
                        player.play(11);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                YoYo.with(Techniques.Tada)
                                        .duration(100)
                                        .repeat(1)
                                        .playOn(button_lt);
                            }
                        });
                        break;
                    case 0x08:
                        player.play(12);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                YoYo.with(Techniques.Bounce)
                                        .duration(100)
                                        .repeat(1)
                                        .playOn(button_rt);
                            }
                        });
                    default:
                }
            }

           else {
                switch (content.get(0)) {
                    case 0x01:
                        player.play(1);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CircularAnim.hide(button_pd).go();
                                CircularAnim.show(button_pd).go();
                            }
                        });
                        break;
                    case 0x02:

                        player.play(1);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CircularAnim.hide(button_pd).go();
                                CircularAnim.show(button_pd).go();
                            }
                        });
                        break;
                    case 0x04:
                        player.play(6);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CircularAnim.hide(button_lt).go();
                                CircularAnim.show(button_lt).go();
                            }
                        });
                        break;
                    case 0x08:
                        player.play(4);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CircularAnim.hide(button_rt).go();
                                CircularAnim.show(button_rt).go();
                            }
                        });
                        break;
                    default:
                }
            }
        }
    }


    @Override
    public void onBackPressed() {
        BaseApplication.getInstance().finishAll();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display_gesture);
//        button_0 = (Button)findViewById(R.id.btn_0);
//        button_1 = (MorphingButton) findViewById(R.id.btn_1);
//        button_lt = (Button)findViewById(R.id.btn_lt);
//        button_rt= (Button)findViewById(R.id.btn_rt);
//        button_pd = (Button)findViewById(R.id.btn_pd);
//        button_biubiu= (Button)findViewById(R.id.btn_biubiu);
//        button_biubiu.setOnClickListener(this);
//        button_pd.setOnClickListener(this);
//        button_rt.setOnClickListener(this);
//        button_lt.setOnClickListener(this);
//        button_1.setOnClickListener(this);
//        button_0.setOnClickListener(this);

        //TODO:collect mobile phone data;
        btn_excel = (Button)findViewById(R.id.btn_excel);
        btn_excel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    String uploadFilePath = ExcelUtil.writeExcel(GestureActivity.this,cells,"sensor");
                    loadOss(uploadFilePath);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        });
        initOss();


        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
//        btn_open = (Button)findViewById(R.id.btn_open);
//        btn_to = (Button)findViewById(R.id.btn_to);
//        btn_rescan=(Button)findViewById(R.id.btn_rescan);
//        btn_scan = (Button)findViewById(R.id.btn_scan);

//        mbleService=RxBleService.getInstance();
//        sendFlag = true;
//        FirstScreen firstScreen = new FirstScreen(this);
//        firstScreen.show(R.drawable.naixu,1000,FirstScreen.FADE_OUT);
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                player.init();
//            }
//        }).start();
//        btn_open.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mbleService.sendCommand(Command.DEVICE_COMMAND_BEGIN_OPEN_MPU);
//                btn_to.setVisibility(View.VISIBLE);
//            }
//        });
//        btn_to.setOnClickListener(new View.OnClickListener(){
//            @Override
//            public void onClick(View v) {
//                mbleService.sendCommand(Command.DEVICE_COMMAND_CHOOSE_INSTRUMENT_DRUM,1000);
//                mbleService.setOnReceivedOKListener(GestureActivity.this);
//                mbleService.dealWithData();
//            }
//        });
//        btn_open.setVisibility(View.INVISIBLE);
//        btn_to.setVisibility(View.INVISIBLE);
//        btn_rescan.setOnClickListener(new View.OnClickListener(){
//            @Override
//            public void onClick(View v) {
//                mbleService.reScan();
//            }
//        });
//        IntentFilter filter = new IntentFilter(Action.MOBILE_SENSOR);
//        registerReceiver(mreceiver,filter);
        //TODO　RxJavaObserver Attempt
            //TODO fix how to obtain async result but not to halt the main thread
        //TODO msendDataState
    }

    //TODO Oss relative
    private void initOss() {
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(OssConst.accessKeyId, OssConst.accessKeySecret);
        oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
    }
    private void loadOss(String absFilePath){
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(OssConst.bucketName, OssConst.objectName, absFilePath);

// 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });

    }

    private int count = 1;

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        Log.i("log", "onAccuracyChanged: yes");
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (count++ % 40 == 0) {
            int type = event.sensor.getType();
            Log.i("onsensorChanged", "onSensorChanged: "+event.values[0]+event.values[1]+event.values[2]);
            if (type == Sensor.TYPE_ACCELEROMETER) {

                if (event.values[2] > 12|| event.values[2] < 2) {
                    mid+=1;
                    if(mid<=100){
                        Cell cell = new Cell();
                        cell.setId(String.valueOf(mid));
                        cell.setX_axis(String.valueOf(event.values[0]));
                        cell.setY_axis(String.valueOf(event.values[1]));
                        cell.setZ_axis(String.valueOf(event.values[2]));
                        cells.add(cell);
                        }
                }
                count = 1;
            }
        }}

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onStop() {
//        mbleService.sendCommand(Command.DEVICE_COMMAND_POWER_OFF);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
//        unregisterReceiver(mreceiver);
        sensorManager.unregisterListener(this);

//        Intent intent = new Intent(this,RxBleService.class);
//        stopService(intent);
        super.onDestroy();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_biubiu:
                mMode=0;
                break;
            case R.id.btn_lt:

                break;
            case R.id.btn_rt:

                break;
            case R.id.btn_pd:

                break;
            case R.id.btn_1:
                mMode = 1;

                break;
            case R.id.btn_0:

                break;
            default:
        }
    }

    public class GestureReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String command = intent.getStringExtra("command");
            switch (command){
                case "service":
                    btn_open.setVisibility(View.VISIBLE);
                    break;
                case "disconnected":
                    Toast.makeText(BaseApplication.getContext(),"disconnected",Toast.LENGTH_SHORT).show();
                    break;
                case 0x03+"":
                    player.play(2);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            CircularAnim.hide(button_biubiu).go();
                            CircularAnim.show(button_biubiu).go();
                        }
                    });
                    break;
                default:

            }
        }
    }
}